package cn.yunlang.zhangZhongFei.controller;

import cn.yunlang.zhangZhongFei.vo.response.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Api(tags = "文件上传模块")
@RestController
@RequestMapping("api/upload")
@Slf4j
public class UploadFileController {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.access-url}")
    private String accessUrl;

    @Value("${spring.profiles.active}")
    private String active;

    @Value("${file.upload.hostAddress}")
    private String hostAddress;

    @Value("${server.port}")
    private String port;

    @ApiOperation("文件上传")
    @PostMapping(value = "/uploadFile", consumes = "multipart/form-data")
    public R<String> uploadFile(
            @ApiParam(value = "文件", required = true)
            @RequestPart("file") MultipartFile file) {

        if (file.isEmpty()) {
            return R.error(400, "上传文件不能为空");
        }

        try {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成新文件名
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

            // 确保上传目录存在
            long time = new Date().getTime();
            File uploadDir = new File(uploadPath + time);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件
            File destFile = new File(uploadDir +"\\"+ fileName);
            file.transferTo(destFile);

            // 返回文件访问URL
            String fileUrl ="";
            if (active.equals("dev")) {
                fileUrl = "http://" + hostAddress + ":" + port + "/file/" + time + "/" + fileName;
            } else {
                fileUrl = "https://" + hostAddress + "/file/" + time + "/" + fileName;
            }
            log.info("文件上传成功：{}", fileUrl);

            return R.success(fileUrl);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return R.error(500, "文件上传失败：" + e.getMessage());
        }
    }
}
